﻿using System;
using System.Data;
using System.Web.UI;
using Telerik.Web.UI;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.MODEL;
using KPIS.DBM;
using System.IO;

namespace KPIS.GERP.GBMS.APP_UI
{
    public partial class BGM_RequestProject : System.Web.UI.Page
    {
        private ComboBLL comboBLL = new ComboBLL();
        private SystemControlBLL scBLL = new SystemControlBLL();
        private IProjectControl projectBLL;
        string type;
        int year = SystemInfo._CurrentYearReq;

        protected void Page_Load(object sender, EventArgs e)
        {
            type = Request.QueryString["type"].ToString();

            if (type.Length > 0)
            {
                projectBLL = Project_Factory.GetProjectControlFactory(type);
            }

            if (!IsPostBack)
            {
                LoadYear();
                LoadJobSiteCombo();
                LoadData();
            }
        }

        private void LoadYear()
        {
            int CurrYear = SystemInfo._CurrentYearReq;
            ddlYear.Items.Clear();

            for (int i = CurrYear + 5; i >= CurrYear - 5; i--)
            {
                ddlYear.Items.Add(new RadComboBoxItem(i.ToString(), i.ToString()));
            }
            ddlYear.SelectedValue = CurrYear.ToString();
        }
        private void LoadJobSiteCombo()
        {
            string jobSiteID = (string)new SsMng().GetUss(SsMng.SsUserType.WorkingJobSiteSeq);
            DataTable dt = comboBLL.ListJobsite();
            ddlJobSite.DataSource = dt;
            ddlJobSite.DataBind();

            ddlJobSite.Items.Insert(0, new RadComboBoxItem("----- หน่วยงานทั้งหมด -----", ""));
            ddlJobSite.SelectedValue = jobSiteID;
            if (jobSiteID != scBLL.JobSiteStrategyID())// ยุทธศาสตร์=1300913028       แผน=1300912975
            {
                ddlJobSite.Enabled = false;
                btnExportExcel.Visible = false;
                //ddlYear.AutoPostBack = true;
            }
            else
            {
                ddlJobSite.Enabled = true;
                btnExportExcel.Visible = true;
                //ddlYear.AutoPostBack = false;
            }
        }

        private void LoadData()
        {
            year = int.Parse(ddlYear.SelectedValue);

            gridProject.DataSource = projectBLL.GetDataStrategyControl(year, ddlJobSite.SelectedValue, false, "A");
            gridProject.DataBind();

            gridProjectByOption.DataSource = projectBLL.GetDataProjectByOption(year, ddlJobSite.SelectedValue, "", "A");
            gridProjectByOption.DataBind();

            gridSource.DataSource = projectBLL.GetDataProjectBySequenceForGridIn(year.ToString(), ddlJobSite.SelectedValue, "", "A");
            gridSource.DataBind();

            //ViewState["gridMarket"] = projectBLL.GetDataProjectOption(year.ToString(), ddlJobSite.SelectedValue, "2", "");

            //gridMarket.DataSource = (DataTable)ViewState["gridMarket"];
            //gridMarket.DataBind();

            //ViewState["gridProduct"] = projectBLL.GetDataProjectOption(year.ToString(), ddlJobSite.SelectedValue, "1", "");

            //gridProduct.DataSource = (DataTable)ViewState["gridProduct"];
            //gridProduct.DataBind();

        }

        protected void ddlJobSite_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            //if(ddlJobSite.SelectedValue.Length > 0)
            LoadData();
        }


        protected void gridSource_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_source_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridProject_ItemDataBound(object sender, GridItemEventArgs e)
        {

            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridProjectByOption_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridMarket_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_option_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridProduct_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridFooterItem)
            {
                GridFooterItem footer = (GridFooterItem)e.Item;
                footer["bgm_option_name"].Controls.Add(new LiteralControl("<span style='color: Black; font-weight: bold;'>รวมทั้งหมด :</span> "));
            }
        }

        protected void gridProject_SelectedIndexChanged(object sender, EventArgs e)
        {
            year = int.Parse(ddlYear.SelectedValue);
            var dataItem = gridProject.SelectedItems[0] as GridDataItem;

            gridSource.DataSource = projectBLL.GetDataProjectBySequenceForGridIn(year.ToString(), ddlJobSite.SelectedValue, dataItem["bgm_strat_list_seq"].Text, "A");
            gridSource.DataBind();

            //gridMarket.DataSource = projectBLL.GetDataProjectOption(ddlJobSite.SelectedValue, "2", dataItem["bgm_strat_list_seq"].Text);
            //gridMarket.DataBind();

            //gridProduct.DataSource = projectBLL.GetDataProjectOption(ddlJobSite.SelectedValue, "1", dataItem["bgm_strat_list_seq"].Text);
            //gridProduct.DataBind();
        }

        protected void ddlYear_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if(ddlJobSite.Text.Length > 0)
                LoadData();
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            IDBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);
            DataTable ResultDTB = new DataTable();
            DataTable dtb;
            dbManager.Open();

            try
            {
                string strSQL = "select e2.bgm_exp_seq, e2.bgm_exp_code, e2.bgm_exp_name"
                    + " from bgm_mas_expense e1"
                    + " inner join bgm_mas_expense e2 on e1.bgm_exp_seq = e2.upper_bgm_exp_seq"
                        + " and e2.record_status not like 'D'"

                    + " where e1.upper_bgm_exp_seq is null"
                    + " and e1.record_status not like 'D'"
                    + " order by e2.bgm_exp_code";
                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                ResultDTB.Columns.Add("bgm_strat_list_name");

                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    ResultDTB.Columns.Add(dtb.Rows[i]["bgm_exp_name"].ToString());
                }

                strSQL = "select t.bgm_strat_list_code, t.bgm_strat_list_name"
                    + ", t.bgm_exp_seq, t.bgm_exp_code, t.bgm_exp_name"
                    + ", sum(coalesce(t.total_amount, 0)) as total_amount"

                    + " from ("
                        + " select sdl.bgm_strat_list_code, sdl.bgm_strat_list_name"
                        + ", re.bgm_exp_seq, e.bgm_exp_code, e.bgm_exp_name"
                        + ", re.total_amount"
                        + " from bgm_request r"
                        + " inner join bgm_request_expense re on r.bgm_req_seq = re.bgm_req_seq"
                        + " inner join bgm_mas_expense e1 on re.bgm_exp_seq = e1.bgm_exp_seq"
                        + " inner join bgm_mas_expense e on e1.upper_bgm_exp_seq = e.bgm_exp_seq"
                        + " inner join bgm_strategy_data_list sdl on r.bgm_strat_list_seq = sdl.bgm_strat_list_seq"
                        + " where r.bgm_year = " + ddlYear.SelectedValue
                        + " and re.bgm_source_seq = 1"
                    + ") t"
                    + " group by t.bgm_strat_list_code, t.bgm_strat_list_name"
                        + ", t.bgm_exp_seq, t.bgm_exp_name"
                    + " order by t.bgm_strat_list_code, t.bgm_exp_code";
                dtb = dbManager.ExecuteDataSet(CommandType.Text, strSQL).Tables[0];

                string strOldBgmStratListCode = "";
                string strBgmStratListCode = "";
                string strBgmStratListName = "";
                string strBgmExpName = "";
                double dTotalAmount = 0;
                int j = -1;
                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    strBgmStratListCode = dtb.Rows[i]["bgm_strat_list_code"].ToString();

                    if (strOldBgmStratListCode != strBgmStratListCode)
                    {
                        strOldBgmStratListCode = strBgmStratListCode;
                        strBgmStratListName = dtb.Rows[i]["bgm_strat_list_name"].ToString();
                        ResultDTB.Rows.Add(strBgmStratListName);
                        j++;
                    }

                    strBgmExpName = dtb.Rows[i]["bgm_exp_name"].ToString();
                    dTotalAmount = Convert.ToDouble(dtb.Rows[i]["total_amount"]);
                    ResultDTB.Rows[j][strBgmExpName] = dTotalAmount;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                dbManager.Close();
            }

            Excel_FromDataTable(ResultDTB);
        }

        private void Excel_FromDataTable(DataTable dtb)
        {
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("content-disposition", "attachment; filename=BudgetRequest-" + ddlYear.SelectedValue + ".xls");
            //Response.Charset = "";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);

            grdExcel.Visible = true;
            grdExcel.DataSource = dtb;
            grdExcel.DataBind();
            grdExcel.RenderControl(hw);

            Response.Write(tw.ToString());
            Response.End();
        }

        protected void btnBiRequest_Click(object sender, EventArgs e)
        {
            //panel3.Visible = true;
            //panel2.Visible = false;
            //btnBiRequest.Visible = false;
            //btnGridRequest.Visible = true;

            //BI_BGM_Request1.LoadSubActChart(ddlYear.SelectedValue, null, ddlJobSite.SelectedValue);
        }

        //protected void btnGridRequest_Click(object sender, EventArgs e)
        //{
        //    panel3.Visible = false;
        //    panel2.Visible = true;
        //    btnBiRequest.Visible = true;
        //    btnGridRequest.Visible = false;
        //}
    }
}
